package com.LeeCode;

/**
 * 搜索二维矩阵
 */

public class Code074 {
    public static void main(String[] args) {
        int[][] matrix = {{1}};
        System.out.println(new Code074().searchMatrix2(matrix, 1));

    }

    // 暴力搜索
    public boolean searchMatrix(int[][] matrix, int target) {
        int row = matrix.length, col = matrix[0].length;

        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if (matrix[i][j] == target) {
                    return true;
                }
            }
        }
        return false;
    }

    // 二维二分查找
    public boolean searchMatrix1(int[][] matrix, int target) {
        int row = matrix.length, col = matrix[0].length;
        boolean flag = false;
        int left = 0, right = row - 1, mid;
        while (left <= right) {
            mid = (left + right) / 2;
            if (target == matrix[mid][0]) {
                return true;
            } else if (target > matrix[mid][0]) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        int row_index = right;
        // 判断row_index 是否有效
        if (row_index < 0 || row_index >= row) {
            return false;
        }
        left = 0;
        right = col - 1;
        while (left <= right) {
            mid = (left + right) / 2;
            if (target == matrix[row_index][mid]) {
                return true;
            } else if (target > matrix[row_index][mid]) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return false;
    }

    // 当成一维数组做
    public boolean searchMatrix2(int[][] matrix, int target) {
        int row = matrix.length, col = matrix[0].length;
        int left = -1, right = row * col;
        while (left + 1 < right) {
            int mid = left + (right - left) / 2;
            int x = mid / col, y = mid % col;
            if (matrix[x][y] >= target)
                right = mid;
            else
                left = mid;
        }
        return right != row * col && matrix[right / col][right % col] == target;
    }
}
